<?php

declare (strict_types=1);

namespace app\admin\model\admin;

use app\common\library\helper;
use app\common\model\admin\Role as RoleModel;
use app\admin\model\admin\RoleMenu as RoleMenuModel;
use app\admin\model\admin\UserRole;
use think\db\exception\DbException;
use think\Paginator;

/**
 * 部门记录表模型
 * Class Department
 * @package app\admin\model\system
 */
class Role extends RoleModel
{
    //开启自动时间戳
//    protected $autoWriteTimestamp = false;
    protected $updateTime = false;

    /**
     * 获取列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->with(['admin_user', 'role_type', 'roleMenu'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['sort' => 'desc', 'create_time' => 'desc'])
            ->paginate($param['pageSize'] ?? 10)->toArray();
        $list['data'] = $this->getRoleMenuIds($list['data']);
        return $list;
    }

    /**
     * 整理菜单的api ID集
     * @param $list
     * @return mixed
     */
    private function getRoleMenuIds($list)
    {
        foreach ($list as &$item) {
            if (!empty($item['roleMenu'])) {
                $item['menuIds'] = helper::getArrayColumn($item['roleMenu'], 'menu_id');
            }
        }
        return $list;
    }

    /**
     * 获取所有列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getAllList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->with(['admin_user', 'role_type', 'role_menu'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['sort' => 'desc', 'create_time' => 'desc'])
            ->select();
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'search' => '',
        ]);

        $filter = [];
        !empty($params['search']) && $filter[] = ["role_name", "like", "%{$params['search']}%"];

        if (!empty($params['create_time'])) {
            $times = between_time($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data, $admin)
    {
        if (empty($data['menus'])) {
            $this->error = '菜单权限不能为空，请重新选择';
            return false;
        }

        $this->transaction(function () use ($data, $admin) {
            // 新增角色记录
            $data['admin_user_id'] = $admin['user']['admin_user_id'];
            $this->save($data);

            // 新增角色菜单关系记录
            RoleMenuModel::increased((int)$this['role_id'], $data['menus']);
            // 新增操作日志
            OperationLog::recordLog('新增', "新增角色【{$data['role_name']}】", $admin['user']['admin_user_id']);
        });


        return true;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data, $admin)
    {
        if (empty($data['menus'])) {
            $this->error = '菜单权限不能为空，请重新选择';
            return false;
        }
        $this->transaction(function () use ($data, $admin) {
            // 更新角色记录
            $this->allowField(['role_name', 'status', 'sort'])->save($data);
            // 更新角色菜单关系记录
            RoleMenuModel::updates((int)$this['role_id'], $data['menus']);
            // 新增操作日志
            OperationLog::recordLog('编辑', "编辑角色【{$this->role_name}】", $admin['user']['admin_user_id']);
        });
        return true;
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 批量软删除
     * @return false|int
     */
    public function batchSetDelete($ids)
    {
        return $this->where($this->getPk(), 'in', $ids)->save(['is_delete' => 1]);
    }

    /**
     * 删除记录
     * @return bool
     * @throws Exception
     */
    public function remove()
    {
        // 判断是否存在下级角色
        if (static::detail(['parent_id' => $this['role_id']])) {
            $this->error = '当前角色下存在子角色，不允许删除';
            return false;
        }
        // 判断当前角色下存在用户
        if (UserRole::isExistsUserByRoleId($this['role_id'])) {
            $this->error = '当前角色下存在用户，不允许删除';
            return false;
        }
        // 删除对应的菜单关系
        RoleMenu::deleteAll(['role_id' => $this['role_id']]);
        return $this->delete();
    }
}
